package com.lingdong.onlinejudge.judge.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingdong.onlinejudge.common.ErrorCode;
import com.lingdong.onlinejudge.exception.BusinessException;
import com.lingdong.onlinejudge.judge.codesandbox.CodeSandbox;
import com.lingdong.onlinejudge.judge.codesandbox.CodeSandboxFactory;
import com.lingdong.onlinejudge.judge.codesandbox.model.ExecuteCodeRequest;
import com.lingdong.onlinejudge.judge.codesandbox.model.ExecuteCodeResponse;
import com.lingdong.onlinejudge.judge.service.JudgeService;
import com.lingdong.onlinejudge.judge.strategy.DefaultJudgeStrategy;
import com.lingdong.onlinejudge.judge.strategy.JudgeContext;
import com.lingdong.onlinejudge.judge.strategy.JudgeStrategy;
import com.lingdong.onlinejudge.mapper.SubmitMapper;
import com.lingdong.onlinejudge.mapper.TopicMapper;
import com.lingdong.onlinejudge.model.dto.submit.JudgeInfo;
import com.lingdong.onlinejudge.model.dto.topic.JudgeCase;
import com.lingdong.onlinejudge.model.dto.topic.JudgeConfig;
import com.lingdong.onlinejudge.model.entity.Submit;
import com.lingdong.onlinejudge.model.entity.Topic;
import com.lingdong.onlinejudge.model.enums.JudgeInfoMessageEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private SubmitMapper submitMapper;

    @Resource
    private TopicMapper topicMapper;


    @Override
    public Submit doJudge(Long submitId) {
        QueryWrapper<Submit> submitQueryWrapper = new QueryWrapper<>();
        submitQueryWrapper.eq("id", submitId);
        Submit submit = submitMapper.selectOne(submitQueryWrapper);
        if (submit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 查询题目
        Long topicId = submit.getTopicId();
        QueryWrapper<Topic> topicQueryWrapper = new QueryWrapper<>();
        topicQueryWrapper.eq("id", topicId);
        Topic topic = topicMapper.selectOne(topicQueryWrapper);
        if (topic == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        // 更改题目状态 如果题目的提交状态不为等待中就不用重复执行
        Integer submitStatus = submit.getSubmitStatus();
        // 等待中
        if (submitStatus != 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目已在判题中");
        }
        Submit updateSubmit = new Submit();
        updateSubmit.setId(submitId);
        updateSubmit.setSubmitStatus(1);
        int update = submitMapper.updateById(updateSubmit);
        if (update == 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目状态更新失败");
        }
        String submitCode = submit.getSubmitCode();
        String judgeCaseStr = topic.getJudgeCase();
        List<JudgeCase> judgeCases = JSONArray.parseArray(judgeCaseStr, JudgeCase.class);
        // 获取输入用例
        List<String> inputList = judgeCases.stream()
                .map(JudgeCase::getInput).collect(Collectors.toList());
        // 调用代码沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance("remote");
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(ExecuteCodeRequest.builder()
                .inputList(inputList)
                .code(submitCode)
                .language("java")
                .build());
        // 根据执行结果判断题目状态和信息
        List<String> outputList = executeCodeResponse.getOutputList();
        // 构造上下文
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCases);
        judgeContext.setTopic(topic);
        // 策略模式
        JudgeStrategy judgeStrategy = new DefaultJudgeStrategy();
        JudgeInfo judgeInfo = judgeStrategy.doJudge(judgeContext);
        // 更新数据库
        updateSubmit.setId(submitId);
        updateSubmit.setSubmitStatus(judgeInfo.isSuccess() ? 2 : 3);
        updateSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        updateSubmit.setJudgeTime(new Date());
        int updateInfo = submitMapper.updateById(updateSubmit);
        if (updateInfo == 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目状态更新失败");
        }
        Submit newSubmit = submitMapper.selectOne(submitQueryWrapper);
        if (newSubmit == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目状态更新失败");
        }
        return newSubmit;
    }
}
